package com.qiyadeng.thread;

import java.util.ArrayList;
import java.util.List;

public class TreeNode {	
	  TreeNode parent   = null;  
	  List children = new ArrayList();

	  public synchronized void addChild(TreeNode child){
		  System.out.println(Thread.currentThread().getId()+"addChild "+child);
	    if(!this.children.contains(child)) {
	      this.children.add(child);
	      System.out.println(Thread.currentThread().getId()+"before get parent locker");
	      child.setParentOnly(this);
	    }
	    System.out.println(Thread.currentThread().getId()+"exit addChild");
	  }
	  
	  public synchronized void addChildOnly(TreeNode child){
		System.out.println(Thread.currentThread().getId()+" add child now");
	    if(!this.children.contains(child)){
	      this.children.add(child);
	    }
	  }
	  
	  public synchronized void setParent(TreeNode parent){
		  System.out.println(Thread.currentThread().getId()+"setParent "+parent);
	    this.parent = parent;
	    System.out.println(Thread.currentThread().getId()+"before get child locker");
	    parent.addChildOnly(this);
	    System.out.println(Thread.currentThread().getId()+"exit setParent");
	  }

	  public synchronized void setParentOnly(TreeNode parent){
		  System.out.println(Thread.currentThread().getId()+" set parent now");
	    this.parent = parent;
	  }
}
